# -*- coding: utf-8 -*-

###########################################################################
#
#   Copyright (c) 2020  Bresee, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###########################################################################


import time
import utils.pgsql.base.pgconn as pgconn

"""
pay management
add 
delete
modify
...
"""
_tblName = "tbl_pay"

_DB_SCRIPT = f"""
CREATE TABLE IF NOT EXISTS {_tblName} (
                "payId" SERIAL PRIMARY KEY ,       
                "outTradeNo"  VARCHAR(256) NOT NULL default '' unique,    
                "transactionId" VARCHAR(256) NOT NULL default '' unique, 
                "channelId"  INTEGER NOT NULL default 0, 
                "channelInfo" VARCHAR(256) NOT NULL default '',  
                "openId" VARCHAR(256) NOT NULL default '',  
                "productId" VARCHAR(256) NOT NULL default '',  
                "videoUrl" VARCHAR(256) NOT NULL default '',  
                "duration" VARCHAR(256) NOT NULL default '',  
                "thumbImageUrl" VARCHAR(256) NOT NULL default '',     
                "caseId"  INTEGER NOT NULL default 0, 
                "caseName" VARCHAR(256) NOT NULL default '',     
                "date" VARCHAR(32) NOT NULL default '',   
                "createTime"  VARCHAR(64) NOT NULL default '',   
                "endTime"  VARCHAR(64) NOT NULL default '',     
                "totalFee" INTEGER NOT NULL default 0,  
                "cashFee" INTEGER NOT NULL default 0,   
                "refund" INTEGER NOT NULL default 0,     
                "updateTime" VARCHAR(32) NOT NULL default ''
                );
"""


class PgPay:
    def __init__(self):
        self._pgConn = pgconn.pgMainConn

    def __del__(self):
        pass

    def createTbl(self):
        """
        create
        :return:
        """
        return self._pgConn.exec(_DB_SCRIPT)

    def addpay(self, dic) -> str:
        if "createTime" not in dic:
            dic["createTime"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

        sql_key = '\"' + '\", \"'.join(dic.keys()) + '\"'
        sql_val = ''
        for key in dic:
            if type(dic[key]) is str:
                sql_val = sql_val + '\'' + dic[key] + '\','
            else:
                sql_val = sql_val + str(dic[key]) + ' ,'

  
        sql = "insert into {} ({}) values ({}) ".format(_tblName, sql_key, sql_val[:-1])
        return self._pgConn.exec(sql)

    def modify(self, outTradeNo, cashfee, dic) -> bool:
        dic["updateTime"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

        sql_key = ''
        for key in dic:
            if type(dic[key]) is str:
                sql_key = sql_key + '\"' + key + '\"' + ' = \'' + dic[key] + '\','
            else:
                sql_key = sql_key + '\"' + key + '\"' + ' = ' + str(dic[key]) + ' ,'


        sql =  "update {} set {} where  ".format(_tblName, sql_key[:-1]) + f""" "outTradeNo" = '{outTradeNo}' and "totalFee" = '{cashfee}' """

        return self._pgConn.exec(sql)

    def allCase(self, caseId) -> list:
        sql = f"""select * from {_tblName} where "caseId" = {caseId} order by "createTime" desc LIMIT 200"""
        return self._pgConn.exec_fetchall(sql)

    def PageCase(self, caseId, pageNo, pageSize) -> list:
        sql = f"""select * from {_tblName} where "caseId" = {caseId} order by "createTime" LIMIT {pageSize} OFFSET {(pageNo-1) * pageSize}"""
        return self._pgConn.exec_fetchall(sql)

    def PageAll(self, pageNo, pageSize) -> list:
        sql = f"""select * from {_tblName} order by "createTime" LIMIT {pageSize} OFFSET {(pageNo-1) * pageSize}"""
        return self._pgConn.exec_fetchall(sql)

    def GetAllYesterDay(self, date) -> list:
        sql = f"""select * from {_tblName} where Date("updateTime") = '{date}' order by "createTime" """
        return self._pgConn.exec_fetchall(sql)

    def chanpay(self, channelId, startTime, endTime, caseId=None) -> list:
        tmp = f' and "caseId"={caseId} ' if caseId else ""
        sql = "select * from tbl_techpay  where \"templateName\" SIMILAR TO '%{}%' {} and  \"createTime\" between '{}' and '{}' ".format(
            channelId, tmp, startTime, endTime
        )
        print(sql)

        return self._pgConn.exec_fetchall(sql)

    def chanpaycount(self, caseId, startTime, endTime,play=None) -> list:
        tmp = f" and \"templateName\" SIMILAR TO '%{play}%' " if play else ""
        sql = "select * from tbl_techpay  where \"caseId\" = '{}' and  \"createTime\" between '{}' and '{}'  {} ".format(
            caseId, startTime, endTime,tmp
        )
        print(sql)

        return self._pgConn.exec_fetchall(sql)

    # 获取员工码（订单推荐人）
    def get_case_people(self, caseId):
        sql = f'SELECT * FROM tbl_channel WHERE "caseId" ={caseId}'
        return self._pgConn.exec_fetchall(sql)
